<template>
    <view>
        <view class="wanl-product">
            <!-- 普通布局 -->
            <view class="product_list" :class="dataStyle">
                <block v-for="(item, index) in dataList" :key="index">
                    <block v-if="item.ordergoods">
                        <view class="shop wanl-gray"
                            style="background-color: #fff; width: 100%; border-radius: 20rpx 20rpx 0 0; padding: 20rpx"
                            @tap="onShop(item.ordergoods[0].shop_id)">
                            <text class="wlIcon-dianpu1 wanl-black"></text>
                            <text class="wanl-black margin-lr-xs text-30">{{ item.shop.shopname }}</text>
                            <text class="wlIcon-fanhuigengduo text-sm"></text>
                            <view class="order-head flex justify-between" style="padding-top: 20rpx; ">
                                <text class=" no">订单编号：{{ item.order_no }}</text>
                                <text class="state" v-if="item.order_type == 0">{{
                                    item.state == 1 ? "待支付" : item.state == 2 ? "待发货" : item.state == 3 ? "待收货" :
                                        item.state == 4 ? "待评论" : item.state == 6 ? "已完成" : item.state == 7 ? "已取消" : ''
                                }}</text>
                                <text class="state" v-else>待自提</text>
                            </view>
                        </view>

                    </block>
                    <block v-else>
                        <view class="shop wanl-gray"
                            style="background-color: #fff; width: 100%; border-radius: 20rpx 20rpx 0 0; padding: 20rpx"
                            @tap="onShop(item.shop_id)">
                            <text class="wlIcon-dianpu1 wanl-black"></text>
                            <text class="wanl-black margin-lr-xs text-30">{{ item.shop.shopname }}</text>
                            <text class="wlIcon-fanhuigengduo text-sm"></text>
                            <view class="order-head flex justify-between" style="padding-top: 20rpx; ">
                                <text class="no">订单编号：{{ item.order_sn }}</text>
                                <text class="state" v-if="item.order_type == 0">{{
                                    item.status == 0 ? "待支付" : item.status == 1 ? "待发货" : item.status == 1 ? "待发货" :
                                        item.status == 2 ? "待自提" :
                                            item.status == 3 ? "待收货" : item.status == 4 ? "已完成" : item.status == -1 ? "已取消" : ""
                                }}</text>
                                <text class="state" v-else>待核销</text>
                            </view>
                        </view>
                    </block>
                    <view class="item" @tap.stop="handleGoods(item.id)"
                        style="border-radius: 0 0 20rpx 20rpx !important;">
                        <block v-if="item.ordergoods">
                            <block v-for="(subItem, subIndex) in item.ordergoods" :key="subIndex">
                                <view class="img-wrap">
                                    <image :src="$wanlshop.oss(subItem.image, 125, 125)" mode="aspectFill"></image>
                                </view>

                                <view class="padding-sm" style="
                                        display: flex;
                                        flex: 1;
                                        flex-direction: column;
                                        justify-content: space-around !important;
                                    ">
                                    <view class="">
                                        <view class="text-cut-2">
                                            <text>{{ subItem.title }}</text>
                                        </view>
                                        <view class="goods-tag"> </view>
                                    </view>
                                    <view class="text-red text-bold text-lg" v-if="subItem.price">
                                        <text class="text-price">{{ subItem.price }}</text>
                                        <text class="num" style="margin-left: 20rpx; font-size: 24rpx; color: #999">
                                            X{{ subItem.number }}</text>
                                        <view style="float: right;">
                                            <button class="cu-btn round wanl-bg-orange"
                                                v-if="item.order_type == 0 && item.state == 2"
                                                @click.stop="onWriteOff(item.id, 'goods')" style="width: 200rpx">
                                                去发货
                                            </button>
                                        </view>
                                    </view>
                                </view>

                            </block>

                        </block>
                        <block v-else>
                            <view class="img-wrap">
                                <image :src="$wanlshop.oss(item.goods_image, 125, 125)" mode="aspectFill"></image>
                            </view>

                            <view class="padding-sm"
                                style="display: flex; flex-direction: column; justify-content: space-around !important;flex: 1;">
                                <view class="">
                                    <view class="text-cut-2">
                                        <text>{{ item.goods_name }}</text>
                                    </view>
                                    <view class="goods-tag"> </view>
                                    <text class="num"
                                        style="width: 100%;display: block;text-align: right;font-size: 24rpx;"> X{{
                                            item.goods_num
                                        }}</text>
                                </view>
                                <view class="jfen flex f-20" v-if="item.score">
                                    <view class="flex left">
                                        <image class="jifen" :src="imageUrl + '/static/images/new/jfen.png'"
                                            mode="scaleToFill" />
                                        <text class="jf">{{ item.score }}积分 </text>
                                    </view>
                                    <text class="add" v-if="item.money > 0">+{{ '¥' + item.money }}</text>
                                </view>
                                <view style="width: 100%;display: flex;justify-content: flex-end">
                                    <button v-if="item.status == 1 && item.order_type == 0"
                                        class="cu-btn round wanl-bg-orange" @click.stop="onWriteOff(item.id, 'score')"
                                        style="width: 200rpx">
                                        去发货
                                    </button>
                                </view>

                            </view>
                        </block>
                    </view>
                </block>
            </view>
        </view>
    </view>
</template>

<script>
/**
 * wanlProduct 商品
 * @description 商品组件 深圳前海万联科技有限公司 https://www.wanlshop.com（除万联官方内嵌系统，未经授权严禁使用）
 * @著作权：WanlShop 登记号：2020SR0255711 版本：V1.0.0
 * @property {Array} dataList 列表数据
 * @property {String} dataStyle 列表样式
 * @example <wanl-product />
 */
export default {
    name: "wanlProduct",
    props: {
        dataList: {
            type: Array,
            required: true,
            default: function () {
                return [];
            },
        },
        dataType: {
            type: String,
            default: "goods",
        },
    },
    data() {
        return {
            imageUrl: this.$imageUrl || "",
            addTime: 180,
            leftList: [],
            rightList: [],
            tempList: [],
            children: [],
            dataStyle: "col-1-10",
        };
    },
    watch: {
        copyFlowList(nVal, oVal) {
            // 取差值，即这一次数组变化新增的部分
            let startIndex = Array.isArray(oVal) && oVal.length > 0 ? oVal.length : 0;
            if (nVal.slice(startIndex).length == 0) {
                this.leftList = [];
                this.rightList = [];
                this.tempList = this.cloneData(this.copyFlowList);
            } else {
                this.tempList = this.tempList.concat(this.cloneData(nVal.slice(startIndex)));
            }
            this.splitData();
        },
    },
    mounted() {
        this.tempList = this.cloneData(this.copyFlowList);
        this.splitData();
    },
    computed: {
        // 破坏flowList变量的引用，否则watch的结果新旧值是一样的
        copyFlowList() {
            return this.cloneData(this.dataList);
        },
    },

    methods: {
        //去发货
        onWriteOff(order_id, type) {
            this.$emit("onWriteOff", order_id, type);
        },
        async splitData() {
            if (!this.tempList.length) return;
            let rightRect = await this.getRect("#wanl-right-cloumn");
            let leftRect = await this.getRect("#wanl-left-cloumn");
            // 如果左边小于或等于右边，就添加到左边，否则添加到右边
            let item = this.tempList[0];
            if (!item) return;
            item.image = this.$wanlshop.oss(item.image, 172, 0, 1);
            item.comment = this.$wanlshop.toFormat(item.comment, "hundred");
            item.praise = item.comment > 0 ? parseInt((item.praise / item.comment) * 100) : 0;
            if (leftRect.height < rightRect.height) {
                this.leftList.push(item);
            } else if (leftRect.height > rightRect.height) {
                this.rightList.push(item);
            } else {
                // 这里是为了保证第一和第二张添加时，左右都能有内容
                // 因为添加第一张，实际队列的高度可能还是0，这时需要根据队列元素长度判断下一个该放哪边
                if (this.leftList.length <= this.rightList.length) {
                    this.leftList.push(item);
                } else {
                    this.rightList.push(item);
                }
            }
            // 移除临时列表的第一项
            this.tempList.splice(0, 1);
            // 如果临时数组还有数据，继续循环
            if (this.tempList.length) {
                setTimeout(() => {
                    this.splitData();
                }, this.addTime);
            }
        },
        // 复制而不是引用对象和数组
        cloneData(data) {
            return JSON.parse(JSON.stringify(data));
        },
        getRect(selector, all) {
            return new Promise((resolve) => {
                let query = null;
                // 支付宝小程序不能加后面的.in(this)，是它自身的限制
                // #ifndef MP-ALIPAY
                query = uni.createSelectorQuery().in(this);
                // #endif
                // #ifdef MP-ALIPAY
                query = uni.createSelectorQuery();
                // #endif
                query[all ? "selectAll" : "select"](selector)
                    .boundingClientRect((rect) => {
                        if (all && Array.isArray(rect) && rect.length) {
                            resolve(rect);
                        }
                        if (!all && rect) {
                            resolve(rect);
                        }
                    })
                    .exec();
            });
        },
        handleGoods(id) {
            console.log(id, this.dataType, '===============id');
            if (this.dataType === "goods") {
                this.onGoods(id);
            } else if (this.dataType === "shop") {
                this.$wanlshop.to(`/pages/user/order/details?id=${id}&mer=mer`);
            } else if (this.dataType === "score") {
                this.$wanlshop.to(`/pages/merchant/merDetail?order_id=${id}`);
            }
        },
    },
};
</script>

<style lang="scss" scoped>
.wanl-waterfall {
    display: flex;
    flex-direction: row;
    align-items: flex-start;

    .wanl-cloumn {
        display: flex;
        flex: 1;
        flex-direction: column;
        height: auto;
        width: 50%;

        .wanl-image {
            width: 100%;
        }
    }
}

.text-linePrice {
    text-decoration: line-through;
    font-weight: normal;
    color: #ccc;
}

.text-linePrice::before {
    content: "¥";
    font-weight: normal;
    color: #ccc;
    margin-left: 10rpx;
}

.jfen {
    margin-top: 20rpx;

    .left {
        background: #fbe7ce;
        border-radius: 6rpx;
        padding: 0 10rpx 0 0;
    }

    .jifen {
        width: 48rpx !important;
        height: 32rpx !important;
    }

    .add {
        margin-left: 10rpx;
        font-size: 24rpx;
        color: #ea321b;
    }
}
</style>
